<template>
  <div class="flex-column">
    <div class="flex justify-between flex-row-reverse">
      <div class="text-right flex justify-end flex-wrap">
        <el-select
          v-model="queryData.status"
          clearable
          filterable
          style="width: 200px"
          class="mr-10 mb-10"
          size="mini"
          :placeholder="$t('EXECUTE_STATUS')"
        >
          <el-option
            v-for="(item, index) in dictList.OTDR_TIME_TEST_STATUS"
            :key="index"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
        <el-date-picker
          v-model="dateRange"
          class="mr-10 mb-10"
          size="mini"
          type="daterange"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          range-separator="-"
          :start-placeholder="$t('START_TIME')"
          :end-placeholder="$t('END_TIME')"
          align="right"
          style="width: 300px"
        />
        <el-input
          v-model.trim="queryData.keyword"
          class="mb-10"
          style="width: 300px"
          maxlength="32"
          clearable
          :placeholder="$t('TEST_NAME') + '/' +$t('LINK_SEGMENT_NAME') + '/' +$t('NODE_NAME')"
          @keyup.enter.native="$debounce(search)"
        />
        <el-button type="primary" class="ml-10 mb-10" @click="$debounce(search)">{{
          $t('QUERY')
        }}</el-button>
      </div>
      <div class="flex-auto mb-10">
        <template>
          <el-button
            v-if="permission.add"
            type="primary"
            icon="el-icon-plus"
            @click="operate({data:null, type:'add'})"
          >{{ $t('ADD') }}</el-button>
        </template>
      </div>
    </div>
    <TableView
      ref="tableView"
      :table-header="tableHeader"
      :table-data="tableData"
      :page-data="pageData"
      :operate-width="190"
      @sortChange="sortChange"
      @operate="operate"
      @pageChange="pageChange"
    />
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import linkTestPlan from '@/api/oen/LinkTestPlan'
  import { deepClone, timeToSec, pickerOptionsClassMonth } from '@/utils/common'
  import TableView from '@/components/TableView'
  let searchData = {} // 查询参数 只有点了查询有效
  export default {
    components: { TableView },
    props: {
      pageName: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        pickerOptions: pickerOptionsClassMonth,
        tableHeader: [
          {
            label: 'TEST_NAME',
            prop: 'planName',
            fixed: 'left',
            configType: 'default',
            width: 140
          },
          {
            label: 'LINK_SEGMENT_NAME',
            prop: 'logicSegment.segmentName',
            width: 100
          },
          {
            label: 'ANODE',
            prop: 'startNodeName',
            width: 100
          },
          {
            label: 'ZNODE',
            prop: 'endNodeName',
            width: 100
          },
          {
            label: 'EXECUTE_STATUS',
            prop: 'statusName'
          },
          {
            label: 'TEST_CYCLE',
            prop: 'gapDay',
            sortable: 'custom',
            width: 100
          },
          {
            label: 'TEST_PERIOD',
            prop: 'testPeriod',
            width: 160
          },
          {
            label: 'START_TIME',
            prop: 'startDate',
            sortable: 'custom',
            width: 100
          },
          {
            label: 'END_TIME',
            prop: 'endDate',
            sortable: 'custom',
            width: 100
          },
          {
            label: 'LAST_EXECUTION_TIME',
            prop: 'lastTestTime',
            sortable: 'custom',
            width: 160
          },
          {
            label: 'NEXT_EXECUTION_TIME',
            prop: 'nextTestTime',
            sortable: 'custom',
            width: 160
          },
          {
            label: 'DESCRIPTION',
            prop: 'description',
            configType: 'extend',
            width: 100
          }
        ],
        pageData: {
          page: 1,
          size: 20,
          total: 0
        },
        queryData: {
          keyword: '',
          status: ''
        },
        dateRange: [],
        tableData: [],
        sortData: {
          field: null,
          type: null
        }
      }
    },
    computed: {
      ...mapGetters(['dictMap', 'dictList']),
      permission() {
        return this.$store.getters.getAuthData('link:routine')
      }
    },
    methods: {
      doLayout() {
        this.$refs.tableView && this.$refs.tableView.resetSizeFn()
      },
      sortChange(data) {
        this.sortData = data
        this.loadData()
      },
      loadData() {
        const queryData = {
          ...{ page: this.pageData },
          ...searchData,
          sort: this.sortData.type ? this.sortData : null
        }
        linkTestPlan.queryPage(queryData).then(res => {
          const listData = res.list || []
          this.tableData = listData.map(i => {
            return {
              ...i,
              startNodeName: i.startNode ? i.startNode.nodeName : '',
              endNodeName: i.endNode ? i.endNode.nodeName : '',
              statusName: this.dictMap.OTDR_TIME_TEST_STATUS[i.status],
              testPeriod: i.startTime + ' - ' + i.endTime,
              nextTestTime: new Date(i.nextTestTime).getTime() >
                new Date(i.endDate + ' 23:59:59').getTime()
                ? '--'
                : i.nextTestTime,
              btns: this.getBtns(i)
            }
          })
          this.pageData.total = res.total
          this.$nextTick(() => {
            this.doLayout()
          })
        })
      },
      getBtns() {
        const btns = [
          {
            key: 'view',
            show: true,
            label: 'VIEW'
          },
          {
            key: 'mod',
            show: this.permission.mod,
            label: 'MOD'
          },
          {
            key: 'copy',
            show: this.permission.plan,
            label: 'REPLICATION_PLAN'
          },
          {
            key: 'del',
            show: this.permission.del,
            label: 'DEL'
          }
        ]
        return btns.filter(i => i.show)
      },
      // 关键字搜索
      search() {
        this.pageData.page = 1
        const time = {}
        if (this.dateRange && this.dateRange.length) {
          time.startDate = this.dateRange[0]
          time.endDate = this.dateRange[1]
        }
        searchData = {
          keyword: this.queryData.keyword.trim(),
          status: this.queryData.status || null,
          sort: this.sortData.type ? this.sortData : null,
          ...time
        }
        this.loadData()
      },
      // 操作
      operate(data) {
        if (data.type === 'mod' && data.data.status === 'EXECUTING') {
          this.$message.error(this.$t('TERMINATE_TASK'))
          return
        }
        if (data.type === 'del') {
          this.del(data.data)
          return
        }
        this.$emit('operate', { rowData: deepClone(data.data), operateType: data.type })
      },
      // 删除
      del(row) {
        const errMsg =
          row.status !== 'EXECUTING' ? this.$t('CONFIRM_DELETION_PROMPT_TIP', { key: this.$t('TEST_PLAN'), value: row.planName }) : this.$t('DEL_EXISTING_ROUTINE')

        this.$confirm(errMsg, { type: 'warning' })
          .then(() => {
            if (row.status !== 'EXECUTING') {
              linkTestPlan
                .delPlan({ id: row.id }, { planName: row.planName, planId: row.planId })
                .then(res => {
                  this.$message.success(this.$t('DELETE_SUCCESS'))
                  this.loadData()
                })
            } else {
              this.$message.error(this.$t('TERMINATE_TASK'))
            }
          })
          .catch(() => {})
      },
      // 是否可删除按钮
      getDel(row) {
        /**
         * 1）未启动执行的任务计划可以删除；
          2）计划时段已启动的任务，如AFS设备在执行任务时间段内则不允许删除；
          3）计划时段已启动的任务，如AFS在执行任务时间段外，该例测计划任务可允许删除，
          同步应终止已创建的任务，提示用户“已创建的例测任务将终止，确认删除例测计划？”；
          4）如果用户还需要删除，提示用户到任务管理->任务列表中先执行任务终止操作；
         */
        if (row.status !== 'EXECUTING') {
          return false
        } else {
          const curHours = new Date().getHours()
          const curMinutes = new Date().getMinutes()
          const curTime = timeToSec(curHours + ':' + curMinutes + ':00')
          return curTime > timeToSec(row.startTime) && curTime < timeToSec(row.endTime)
        }
      },
      pageChange(data) {
        this.pageData = data
        this.loadData()
      }
    }
  }
</script>

<style></style>
